import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { EnumItem } from '@/types/enum'

// 定义枚举数据类型
export interface EnumData {
  [key: string]: EnumItem[]
}

export const useEnumStore = defineStore(
  'enum',
  () => {
    // 枚举缓存
    const enumCache = ref<EnumData>({})
    
    // 加载状态
    const loading = ref<Record<string, boolean>>({})
    
    // 错误状态
    const errors = ref<Record<string, string>>({})

    /**
     * 获取枚举列表
     * @param type 枚举类型
     * @returns 枚举项数组
     */
    const getEnumList = (type: string): EnumItem[] => {
      return enumCache.value[type] || []
    }

    /**
     * 检查枚举是否已加载
     * @param type 枚举类型
     * @returns 是否已加载
     */
    const isEnumLoaded = (type: string): boolean => {
      return !!enumCache.value[type]
    }

    /**
     * 加载枚举数据
     * @param type 枚举类型
     */
    const loadEnum = async (type: string): Promise<EnumItem[]> => {
      // 如果已加载，直接返回
      if (isEnumLoaded(type)) {
        return getEnumList(type)
      }

      // 如果正在加载，返回空数组（实际项目中可以加等待）
      if (loading.value[type]) {
        return []
      }

      try {
        loading.value[type] = true
        errors.value[type] = ''

        // 这里模拟API调用，实际项目中替换为真实API
        const response = await fetchEnumData(type)
        
        if (response.success && response.data) {
          enumCache.value[type] = response.data
          return response.data
        } else {
          throw new Error(response.message || '获取枚举数据失败')
        }
      } catch (error) {
        const errorMessage = error instanceof Error ? error.message : '未知错误'
        errors.value[type] = errorMessage
        console.error(`加载枚举 ${type} 失败:`, error)
        return []
      } finally {
        loading.value[type] = false
      }
    }

    /**
     * 批量加载枚举
     * @param types 枚举类型数组
     */
    const loadEnums = async (types: string[]): Promise<Record<string, EnumItem[]>> => {
      const promises = types.map(type => loadEnum(type))
      const results = await Promise.all(promises)
      
      const result: Record<string, EnumItem[]> = {}
      types.forEach((type, index) => {
        result[type] = results[index] || []
      })
      
      return result
    }

    /**
     * 清除枚举缓存
     * @param type 枚举类型，不传则清除所有
     */
    const clearCache = (type?: string) => {
      if (type) {
        delete enumCache.value[type]
        delete loading.value[type]
        delete errors.value[type]
      } else {
        enumCache.value = {}
        loading.value = {}
        errors.value = {}
      }
    }

    /**
     * 重新加载枚举
     * @param type 枚举类型
     */
    const reloadEnum = async (type: string): Promise<EnumItem[]> => {
      clearCache(type)
      return await loadEnum(type)
    }

    return {
      enumCache,
      loading,
      errors,
      getEnumList,
      isEnumLoaded,
      loadEnum,
      loadEnums,
      clearCache,
      reloadEnum
    }
  },
  {
    persist: {
      key: 'enum-store',
      storage: localStorage,
      paths: ['enumCache']
    }
  }
)

/**
 * 模拟API调用 - 实际项目中替换为真实API
 */
async function fetchEnumData(type: string): Promise<{
  success: boolean
  data?: EnumItem[]
  message?: string
}> {
  // 模拟网络延迟
  await new Promise(resolve => setTimeout(resolve, 300))
  
  // 模拟不同枚举类型的数据
  const mockData: Record<string, EnumItem[]> = {
    stationEnable: [
      { value: '0', label: '禁用' },
      { value: '1', label: '启用' }
    ],
    stationType: [
      { value: '1', label: '充电站' },
      { value: '2', label: '换电站' },
      { value: '3', label: '综合站' }
    ],
    deviceStatus: [
      { value: '0', label: '离线' },
      { value: '1', label: '在线' },
      { value: '2', label: '故障' },
      { value: '3', label: '维护中' }
    ],
    orderStatus: [
      { value: '0', label: '待支付' },
      { value: '1', label: '已支付' },
      { value: '2', label: '进行中' },
      { value: '3', label: '已完成' },
      { value: '4', label: '已取消' }
    ]
  }
  
  const data = mockData[type] || []
  
  return {
    success: true,
    data
  }
}